﻿using System;
using System.Web;
using System.Linq;
using System.Collections.Generic;
using Newtonsoft.Json;
using Fly.Common.Linq;
using RN.ERP.Web.ModelService;

namespace RN.ERP.Web.Handlers
{
    /// <summary>
    /// ComboBoxHandler 的摘要说明
    /// </summary>
    public class ComboBoxHandler : IHttpHandler
    {
        private EnterpriseService.EnterpriseServiceClient enterpriseServiceClient = new EnterpriseService.EnterpriseServiceClient();
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            string action = context.Request["action"];
            string result = string.Empty;
            switch (action)
            {
                case "RelCorp":
                    result = GetRelCorp(context);
                    break;
                default: break;
            }
            context.Response.Write(result);
        }

        private string GetRelCorp(HttpContext context)
        {
            var key = context.Request["key"];
            return(JsonConvert.SerializeObject(CorpSearch(key)));
        }

        private object CorpSearch(string key)
        {     
            var list = new List<ComboxNode>();
            if (!string.IsNullOrEmpty(key))
            {
                var queryCondition = GetCondition(key);
                var corp = enterpriseServiceClient.GetCompanyAllInfo(queryCondition, 20, 1, "02");
                var corpInfo = JsonConvert.DeserializeObject<IList<CompanyInfo>>(corp);
                if (corpInfo != null)
                {
                    list = corpInfo.Select(o => new ComboxNode
                    {
                        id = o.ID,
                        name = o.CorpName,
                        value = o.CorpUserGuid.ToString()
                    }).ToList();
                }
            }

            return list;
        }

        private string GetCondition(string key)
        {
            List<QueryCompanyInfoCondition> queryCompanyInfoList = new List<QueryCompanyInfoCondition>();
            QueryCompanyInfoCondition queryCompanyInfoCondition = new QueryCompanyInfoCondition();
            if (!string.IsNullOrEmpty(key))
            {
                queryCompanyInfoCondition.CorpName = new ParameterValue<string>() { O = OptEnum.Like, V = key };
            }
            queryCompanyInfoList.Add(queryCompanyInfoCondition);
            return JsonConvert.SerializeObject(queryCompanyInfoList);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}